<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class MessageReplyController extends Controller
{
    public function store(Request $request,$id)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'reply_opt_id'     => 'required|integer|min:1',
                'reply_method_id'  => 'required|integer|min:1',
                'token'            => 'required|min:1',
                'attached_msg'     => 'min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        //可回复检验
        $messageResult = DB::table("im_inform_user")
            ->select("im_inform.title","im_inform.set_id","im_inform.close_trigger_type","im_inform.close_trigger_value","im_inform.is_reply_inform","im_inform.send_count","im_inform.sender_id",
                "im_inform_user.user_id","im_inform_user.token",
                "im_inform_user.reply_opt_id","im_inform_user.inform_id")
            ->join("im_inform","im_inform_user.inform_id","=","im_inform.id")
            ->where("im_inform_user.id",$id)
            ->where("im_inform.is_sent",true)
            ->where("im_inform.is_closed",false)
            ->where("im_inform.is_deleted",false)
            ->first();

        if(empty($messageResult))
            return $this::jsonResponse(true,[],"MessageReplyInformClosed");

        if($messageResult->token != $input["token"])
            return $this::jsonResponse(true,[],"MessageReplyTokenError");

        $informId = $messageResult->inform_id;
        $userId   = $messageResult->user_id;

        //更新回复
        $messageReplyData = [
            "reply_opt_id"    => $input["reply_opt_id"],
            "reply_method_id" => $input["reply_method_id"],
            "reply_time"      => date("Y-m-d H:i:s"),
            "attached_msg"    => isset($input["attached_msg"])?$input["attached_msg"]:""
        ];
        $messageReplyResult = DB::table("im_inform_user")->where("id",$id)->update($messageReplyData);

        //停止其他通知渠道
        DB::table("im_inform_user_method")->where("inform_id",$informId)->where("user_id",$userId)->where("send_code",null)->update(["send_code"=>0]);

        //更新回复数量
        if($messageResult->reply_opt_id != null){
            DB::table("im_reply_opt")->where("id",$messageResult->reply_opt_id)->decrement("replied_count");
        }else{
            DB::table("im_inform")->where("id",$informId)->increment("replied_count");
        }
        DB::table("im_reply_opt")->where("id",$input["reply_opt_id"])->increment("replied_count");
        
        $repliedCount = DB::table("im_inform")->where("id",$informId)->pluck("replied_count");
        
        //通知发送人
        // $informTitle   = str_limit($messageResult->title,12,"…");
        // $sendCount     = $messageResult->send_count;
        // $senderId      = $messageResult->sender_id;
        
        // $isReplyInform    = $messageResult->is_reply_inform;
        // $couldReplyInform = ($repliedCount/$sendCount > 0.8 && ($repliedCount-1)/$sendCount <= 0.8) || ($repliedCount/$sendCount == 1);
        // $isFirstReply     = $messageResult->reply_opt_id == null;
        // if($isReplyInform  && $couldReplyInform && $isFirstReply){
        //     if($repliedCount == $sendCount)
        //         $title = "所有人已回复！($informTitle)";
        //     else
        //         $title = "还差".($sendCount - $repliedCount)."人未回复！($informTitle)";

        //     $appId       = $_ENV["PTIME_APP_ID"];
        //     $appSetId    = $_ENV["PTIME_SET_ID"];
        //     $appSenderId = $_ENV["TEAM_SENDER_ID"];
        //     $urlPage     = json_encode([
        //             "page"  =>"inform.show",
        //             "params"=>[
        //                 "tag"=>"stats",
        //                 "id"=>$informId
        //             ]
        //         ]);
        //     $informData = [
        //         "title"     => $title,
        //         "app_id"    => $appId,
        //         "set_id"    => $appSetId,
        //         "sender_id" => $appSenderId,
        //         "users"     =>[["user_id"=>$senderId]],
        //         "is_notcare"=>true,
        //         "reply_opts"=>[
        //             ["content"=>"去看看","is_expected"=>true,"url_page"=>$urlPage],
        //             ["content"=>"好的"]
        //         ]
        //     ];
        //     $informResult = $this->api->with($informData)->post("inform/send");
        // }

        //触发通知关闭-回复人数
        if($messageResult->close_trigger_type == "1"){
            if($messageResult->close_trigger_value == $repliedCount){
                $this->api->put("inform/$informId/close");
            }
        }

        //TODO：触发通知方式发送
        //删除消息提醒
        if($messageResult->reply_opt_id == null){
            $setId  = $messageResult->set_id;
            
            DB::table("im_set_user")
                ->where("inform_id",$informId)
                ->where("user_id",$userId)
                ->update(["is_replied"=>true,"is_viewed"=>true]);

            DB::table("im_set_user")
                ->where("set_id",$setId)
                ->where("user_id",$userId)
                ->where("is_latest",false)
                ->where("is_replied",true)
                ->delete();
        }

        //触发webhook
        $urlHook = DB::table("im_reply_opt")->where("id",$input["reply_opt_id"])->value("url_hook");
        if(!empty($urlHook)){
            $validator = Validator::make(["url_hook"=>$urlHook],["url_hook"=>'url']);
            if($validator->fails())
                return $this::jsonResponse(true,$validator->messages(),"paramError");
            
            $and = strpos($urlHook,"?")?"&":"?";

            $this->curl_get($urlHook."$and"."user_id=$userId");
        }

        return $this::jsonResponse(false,$messageReplyResult);

    }
}